package com.sxbbc.common.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.function.common.GetRest;
import com.function.common.RestResponse;
import com.sxbbc.common.basics.exceptions.ThrowJsonException;
import com.sxbbc.common.basics.utils.calculation.CalcuUtils;
import com.sxbbc.common.basics.utils.date.DateUtil;
import com.sxbbc.common.basics.utils.statics.StaticUtils;
import com.sxbbc.common.core.entity.jz.ActivitySeckillDetail;
import com.sxbbc.common.core.entity.jz.ProSkuDetail;
import com.sxbbc.common.core.entity.jz.ProcMain;
import com.sxbbc.common.core.mapper.jz.ActivitySeckillDetailMapper;
import com.sxbbc.common.core.mapper.jz.ProSkuDetailMapper;
import com.sxbbc.common.core.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxbbc.common.core.service.system.solr.SolrproductService;
import com.sxbbc.common.core.utils.BasePage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 秒杀活动明细表 服务实现类
 * </p>
 *
 * @author leehao
 * @since 2019-06-13
 */
@Service
public class ActivitySeckillDetailServiceImpl extends ServiceImpl<ActivitySeckillDetailMapper, ActivitySeckillDetail> implements IActivitySeckillDetailService {

    @Autowired
    private IProcMainService procMainService;
    @Autowired
    private IProSkuDetailService proSkuDetailService;
    @Autowired
    private ProSkuDetailMapper proSkuDetailMapper;
    @Autowired
    private SolrproductService solrProductService;
    @Autowired
    private IActivitySeckillService activitySeckillService;
    @Autowired
    private IInfoParamService infoParamService;
    @Autowired
    private ICPushLogService cPushLogService;

   /* @Override
    public RestResponse addSeckillProduct(SeckillAddVo seckillAddVo) {
        //查询主表信息
        ActivitySeckill activitySeckill = activitySeckillService.getById(seckillAddVo.getSeckillId());
        if (activitySeckill == null) {
            return GetRest.getFail("该活动不存在！");
        }
        if (!CalcuUtils.getInstance().isEquals(activitySeckill.getStatus(), StaticUtils.STATUS_YES)) {
            return GetRest.getFail("该场活动已结束！");
        }
        ProcMain procMain = procMainService.selectOneByProCode(seckillAddVo.getProCode());
        if (procMain == null) {
            return GetRest.getFail("没有该商品！");
        }
        if (StringUtils.isNotBlank(procMain.getActivitySign())
                && !StringUtils.equals(procMain.getActivitySign(),ActivitySignEnums.SECKILL.getName())) {
            return GetRest.getFail("该商品已参加 " + procMain.getActivitySign() + " 活动");
        }
        boolean save = false;
        //商品规格
        ProSkuDetail skuDetail = proSkuDetailMapper.selectById(seckillAddVo.getSkuId());
        if (skuDetail == null) {
            return GetRest.getFail("该商品规格不存在！");
        }
        //规格的库存
        Integer originalStock = skuDetail.getQty();
        //秒杀设置的总数
        Integer seckillStock = seckillAddVo.getTotalNum();
        //规格的库存比设置的限购总数要小
        if (originalStock < seckillStock) {
            return GetRest.getFail(skuDetail.getProCode() + " : " + skuDetail.getSpecName() + " 库存不足");
        }
        //减少商品库存
        skuDetail.setQty(originalStock - seckillStock);
        //关联秒杀主表ID
        skuDetail.setSeckillId(activitySeckill.getId());
        //保存秒杀活动子表
        ActivitySeckillDetail seckillDetail = new ActivitySeckillDetail();
        seckillDetail.setSeckillId(seckillAddVo.getSeckillId());
        seckillDetail.setBid(seckillAddVo.getBid());
        seckillDetail.setProCode(procMain.getProCode());
        seckillDetail.setProName(procMain.getProName());
        seckillDetail.setProUrl(procMain.getProUrl());
        seckillDetail.setCoverUrl(procMain.getCoverUrl());
        seckillDetail.setSkuId(seckillAddVo.getSkuId());
        seckillDetail.setPrice(skuDetail.getPrice());
        seckillDetail.setSeckillPrice(seckillAddVo.getSeckillPrice());
        seckillDetail.setTotalNum(seckillAddVo.getTotalNum());
        //输入了限购数量取限购数量，未输入为0
        if(seckillAddVo.getLimitNum() == null){
            seckillDetail.setLimitNum(0);
        }else{
            seckillDetail.setLimitNum(seckillAddVo.getLimitNum());
        }
        seckillDetail.setSort(seckillAddVo.getSort());
        //检查是否已参加本场秒杀
        ActivitySeckillDetail seckillDetail1 = selectSeckillDetail(seckillDetail);
        if(seckillDetail1 != null && CalcuUtils.getInstance().isEquals(seckillDetail1.getStatus(),StaticUtils.STATUS_YES)){
            return GetRest.getFail("该规格已参加本活动，请勿重复设置！");
        }
        save = super.save(seckillDetail);
        if (!save) {
            throw new ThrowJsonException("添加秒杀商品失败");
        }
        save = proSkuDetailService.updateById(skuDetail);
        if (!save) {
            throw new ThrowJsonException("更新商品规格失败");
        }
        //商品主表的库存变更
        int saveStock = procMain.getQty() - seckillStock;
        procMain.setQty(saveStock);
        procMain.setActivitySign(ActivitySignEnums.SECKILL.getName());
        save = procMainService.updateById(procMain);
        if (!save) {
            throw new ThrowJsonException("更新商品信息失败");
        }
        //暂不更新到solr
        *//*SolrProductDto solrProductDto = solrProductService.selectById(procMain.getProCode());
        if (solrProductDto != null) {
            solrProductDto.setActivitySign(ActivitySignEnums.SECKILL.getName());
        }
        RestResponse solrResult = solrProductService.addProduct(solrProductDto);
        if (!solrResult.isStatus()) {
            throw new ThrowJsonException("更新商品到搜索缓存失败");
        }*//*
        return GetRest.getSuccess("保存成功");
    }*/

    @Override
    public IPage<ActivitySeckillDetail> queryList(BasePage<ActivitySeckillDetail> page, ActivitySeckillDetail seckillDetail) {
        IPage<ActivitySeckillDetail> pageInfo = baseMapper.queryList(page, seckillDetail);
        long currentTime = DateUtil.getInstance().currentTimeMillis();
        for (ActivitySeckillDetail a : pageInfo.getRecords()) {
            if (currentTime >= a.getBeginTime().getTime() && currentTime < a.getOverTime().getTime()) {
                a.setHasBegin(StaticUtils.STATUS_YES);
            }else{
                a.setHasBegin(StaticUtils.STATUS_NO);
            }
            ProcMain procMain = procMainService.selectOneByProCode(a.getProCode());
            a.setProUnit(procMain.getProUnit());
        }
        return pageInfo;
    }

    @Override
    public RestResponse handleSeckillReturnStock(Integer id) {
        boolean save = false;
        ActivitySeckillDetail activitySeckillDetail = super.getById(id);
        if (activitySeckillDetail == null) {
            return GetRest.getFail("该活动不存在！");
        }
        if (CalcuUtils.getInstance().isEquals(activitySeckillDetail.getStatus(),StaticUtils.STATUS_YES)) {
            return GetRest.getFail("进行中的商品无法返回库存！");
        }
        if (CalcuUtils.getInstance().isEquals(activitySeckillDetail.getStockReturn(),StaticUtils.STATUS_YES)) {
            return GetRest.getFail("该商品已操作返回库存，请勿重复操作！");
        }
        //秒杀总库存
        int totalNum = activitySeckillDetail.getTotalNum();
        //秒杀已售库存
        int buyNum = activitySeckillDetail.getBuyNum();
        //秒杀剩余库存
        int leftNum = totalNum - buyNum;
        //剩余数量小于1，该商品无法返回
        if (leftNum < 1) {
            return GetRest.getFail("该商品没有可返回库存！");
        }
        ProcMain procMain = procMainService.selectOneByProCode(activitySeckillDetail.getProCode());
        if (procMain == null) {
            return GetRest.getFail("该商品已不存在！");
        }
        QueryWrapper<ProSkuDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("pro_code",procMain.getProCode()).eq("id",activitySeckillDetail.getSkuId());
        ProSkuDetail proSkuDetail = proSkuDetailService.getOne(wrapper);
        if (proSkuDetail == null) {
            return GetRest.getFail("该商品详情不存在！");
        }
        //秒杀子表库存标记更新
        activitySeckillDetail.setStockReturn(StaticUtils.STATUS_YES);
        activitySeckillDetail.setBuyNum(activitySeckillDetail.getBuyNum() + leftNum);
        save = super.updateById(activitySeckillDetail);
        if (!save) {
            throw new ThrowJsonException("更新秒杀活动信息失败");
        }
        //商品详情表库存变更
        proSkuDetail.setQty(proSkuDetail.getQty() + leftNum);
        proSkuDetail.setSeckillId(null);
        save = proSkuDetailService.updateById(proSkuDetail);
        if (!save) {
            throw new ThrowJsonException("更新商品详情失败");
        }
        //商品表qty变更
        procMain.setQty(procMain.getQty() + leftNum);
        procMain.setActivitySign("");
        save = procMainService.updateById(procMain);
        if (!save) {
            throw new ThrowJsonException("更新商品主信息失败");
        }
        return GetRest.getSuccess("操作成功");
    }

    /**
     * 查询秒杀活动重复性
     * 如果要做公用查询请另外新建方法！！！
     * @param detail
     * @author leehao
     * @return com.sxbbc.common.core.entity.jz.ActivitySeckillDetail
     */
    private ActivitySeckillDetail selectSeckillDetail(ActivitySeckillDetail detail){
        QueryWrapper<ActivitySeckillDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("status",StaticUtils.STATUS_YES);
        if (StringUtils.isNotBlank(detail.getProCode())) {
            wrapper.eq("pro_code",detail.getProCode());
        }
        if (detail.getSkuId() != null) {
            wrapper.eq("sku_id",detail.getSkuId());
        }
        return super.getOne(wrapper);
    }

    /**
     * Arno 查询有效，限时购产品启动时加入缓存
     * @return
     */
	public List<ActivitySeckillDetail> queryIng() {
		return baseMapper.queryIng();
	}

    @Override
    public List<ActivitySeckillDetail> queryValidList(Integer seckillId) {
        return baseMapper.queryValidList(seckillId);
    }
}
